<template>
  <van-form @submit="onSubmit">
    <van-field
      v-model="username"
      name="用户名"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
    />
    <van-field
      v-model="password"
      type="password"
      name="密码"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
    />
    <div style="margin: 16px;">
      <van-button round block type="info" native-type="submit">登录/注册</van-button>
    </div>
  </van-form>
</template>

<script>
import { GetUserLogin } from "@/request/api";
import qs from "qs";
export default {
  data() {
    return {
      username: "",
      password: ""
    };
  },
  methods: {
    onSubmit(values) {
      // 非空判断
      if (!this.username || !this.password) {
        return;
      }
      let data = {
        username: this.username,
        pwd: this.password
      };
      // 发送请求
      GetUserLogin(qs.stringify(data)).then(resp => {
        if (resp.errno == 0) {
          // 设置token
          localStorage.setItem("token", resp.data.token);
          // 获取vuex里的用户信息
          console.log(resp.data.userInfo);
          localStorage.setItem("userInfo", JSON.stringify(resp.data.userInfo));
          this.$toast.success("登录成功");
          this.showLogin();
          window.location.reload();
        } else {
          alert("请求有误");
        }
      });
    },
    showLogin() {
      this.$store.commit("changehideLogin", false);
    }
  }
};
</script>

<style lang="less" scope>
.van-form {
  width: 90%;
  position: absolute;
  left: 50%;
  top: calc(50% - 50px);
  transform: translate(-50%, -50%);
  background-color: #fff;
  z-index: 20;
}
</style>